/*
 * @Author: wangyongcun
 * @Date: 2023-09-06 15:20:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-08 14:07:37
 * @Description: mysql配置
 */
import * as mysql from "mysql";
const { mysqlConfig } = globalConfig;
try {
  log.info(`mysql初始化...`);
  //创建连接池
  const pool = mysql.createPool(mysqlConfig);
  //创建全局db函数
  global.db = (sql, values) => {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        if (err) {
          log.error(`mysql连接失败：${err}`);
          //数据库连接失败
          resolve({
            status: 500,
          });
        } else {
          //数据库连接成功
          connection.query(sql, values, (err, results) => {
            connection.release(); // 释放连接池
            if (err) {
              log.error(`mysql执行失败：${err}`);
              resolve({
                status: 400,
              });
            } else {
              resolve({
                status: 200,
                results,
              });
            }
          });
        }
      });
    });
  };
  log.info(`mysql初始化成功！`);
} catch (err) {
  log.error(`mysql初始化失败：${err}`);
  throw err;
}
